package com.lock;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author:wesley
 */
public class ZookeeperCommon implements Watcher{


    private ZooKeeper zooKeeper;

    private CountDownLatch cd = new CountDownLatch(1);

    private Logger LOGGER = LoggerFactory.getLogger(ZookeeperCommon.class);


    /**
     * zk 连接
     *
     * @param ipAddress
     * @param session_time
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public ZooKeeper connect(String ipAddress,int session_time) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(ipAddress, session_time, this);
        cd.await();
        LOGGER.info("ZK 连接成功.....");
        return zooKeeper;
    }


    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState().equals(Event.KeeperState.SyncConnected)) {
            cd.countDown();
        }
    }


    public void close() throws InterruptedException {
        zooKeeper.close();
    }


}
